function getCookie(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}

//因此开始生成发请求, 和后面的获取短信验证码请求. 都需要用到UUID, 所以需要用全局变量来记录
var imageCodeId = "";

function generateUUID() {
    var d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}

function generateImageCode() {
    // 1. 生成UUID
    imageCodeId = generateUUID()
    // 2. 给image code的img的src属性, 拼接URL即可
    url = "/api/v1_0/image_codes/" + imageCodeId
    $(".image-code>img").attr("src", url)
}

function sendSMSCode() {
    console.log('执行发送短信验证码函数')
    $(".phonecode-a").removeAttr("onclick");
    var mobile = $("#mobile").val();
    if (!mobile) {
        $("#mobile-err span").html("请填写正确的手机号！");
        $("#mobile-err").show();
        $(".phonecode-a").attr("onclick", "sendSMSCode();");
        return;
    }
    var imageCode = $("#imagecode").val();
    if (!imageCode) {
        $("#image-code-err span").html("请填写验证码！");
        $("#image-code-err").show();
        $(".phonecode-a").attr("onclick", "sendSMSCode();");
        return;
    }
    $.get("/api/v1_0/sms_codes/" + mobile, {image_code: imageCode, image_code_id: imageCodeId},
        function (data) {
            if (0 != data.errno) {
                $("#image-code-err span").html(data.errmsg);
                $("#image-code-err").show();
                if (2 == data.errno || 3 == data.errno) {
                    generateImageCode();
                }
                $(".phonecode-a").attr("onclick", "sendSMSCode();");
            }
            else {
                var $time = $(".phonecode-a");
                var duration = 60;
                var intervalid = setInterval(function () {
                    $time.html(duration + "秒");
                    if (duration === 1) {
                        clearInterval(intervalid);
                        $time.html('获取验证码');
                        $(".phonecode-a").attr("onclick", "sendSMSCode();");
                    }
                    duration = duration - 1;
                }, 1000, 60);
            }
        }, 'json');
}

$(document).ready(function () {
    generateImageCode();
    $("#mobile").focus(function () {
        $("#mobile-err").hide();
    });
    $("#imagecode").focus(function () {
        $("#image-code-err").hide();
    });
    $("#phonecode").focus(function () {
        $("#phone-code-err").hide();
    });
    $("#password").focus(function () {
        $("#password-err").hide();
        $("#password2-err").hide();
    });
    $("#password2").focus(function () {
        $("#password2-err").hide();
    });
    $(".form-register").submit(function (e) {
        e.preventDefault();
        mobile = $("#mobile").val();
        phoneCode = $("#phonecode").val();
        passwd = $("#password").val();
        passwd2 = $("#password2").val();
        if (!mobile) {
            $("#mobile-err span").html("请填写正确的手机号！");
            $("#mobile-err").show();
            return;
        }
        if (!phoneCode) {
            $("#phone-code-err span").html("请填写短信验证码！");
            $("#phone-code-err").show();
            return;
        }
        if (!passwd) {
            $("#password-err span").html("请填写密码!");
            $("#password-err").show();
            return;
        }
        if (passwd != passwd2) {
            $("#password2-err span").html("两次密码不一致!");
            $("#password2-err").show();
            return;
        }

        //定义数据 -> JS对象
        var data = {
            mobile: mobile,
            sms_code: phoneCode,
            password: passwd
        }

        //需要转换成JSON格式的字符串
        //X-CSRFToken --> 固定写法,将来对比的时候,就会从这个Key中取值
        // getCookie:自定义从cookie获取csrf_token的方法
        data_json = JSON.stringify(data)


        $.ajax({
            url: "/api/v1_0/users",//请求路径
            type: 'post',//请求方式
            dataType: 'json',//指明后端发送的是JSON数据
            data: data_json,//要发送的数据
            contentType: 'application/json',//指明给后端发送的是JSON数据
            headers: {
                'X-CSRFToken': getCookie('csrf_token')
            }
        }).done(
            function (data) {
                if (data.errno == "0") {
                    //注册成功
                    console.log('注册成功')
                    location.href = '/'
                } else {
                    //注册失败
                    console.log(data.userInfo)
                    console.log(data)
                }
            }
        ).fail(
            function (data) {
                console.log('注册失败')
            }
        )
    });
})